import { observable, action, makeObservable } from 'mobx';
import { store, uuid, extend } from "@/Utils";

class TodoStore {
  constructor() {
    //获取this
    makeObservable(this)
  }

  //声明变量
  @observable key:string = 'react-todos';

  @observable todos:Array<ITodoItem> = store(this.key);

  @observable onChanges:Array<Function> = [];

  //声明函数
  @action
  subscribe = (onChange: Function) => {
    this.onChanges.push(onChange)
  }

  @action
  inform = () => {
    store(this.key, this.todos)
    this.onChanges.forEach(function (cb) {
      cb();
    })
  }

  @action
  addTodo = (title: string) => {
    this.todos = this.todos.concat({
      id: uuid(),
      title,
      completed: false,
    });

    this.inform();
  }

  @action
  toggleAll = (checked: boolean) => {
    this.todos = this.todos.map(function (todo) {
      return extend({}, todo, { completed: checked });
    });

    this.inform();
  }

  @action
  toggle = (todoToToggle: ITodoItem) => {
    this.todos = this.todos.map(function (todo) {
      return todo !== todoToToggle
        ? todo
        : extend({}, todo, { completed: !todo.completed });
    });

    this.inform();
  }

  @action
  destroy = (todo: ITodoItem) => {
    this.todos = this.todos.filter(function (candidate) {
      return candidate !== todo;
    });

    this.inform();
  }

  @action
  save = (todoToSave: ITodoItem, text: string) => {
    this.todos = this.todos.map(todo => {
      return todo !== todoToSave ? todo : extend({}, todo, {title: text})
    })

    this.inform();
  }

  @action
  clearCompleted = () => {
    this.todos = this.todos.filter(function(todo) {
      return !todo.completed
    })

    this.inform();
  }
}
export default TodoStore